<template>
  <el-dialog :title="title" v-model="visible" width="600px">
    <el-tree
        v-if="visible"
        ref="treeRef"
        :data="data"
        show-checkbox
        node-key="id"
        :default-checked-keys="selected"
        :props="treeProps"
        highlight-current
        default-expand-all
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {defineEmits, defineProps, ref, watch} from 'vue';

const props = defineProps({
  data: Array,
  modelValue: Boolean,
  selected: Array,
  title: String,
  keyProp: {type: String, default: 'id'},
  labelProp: {type: String, default: 'name'}
});
const emit = defineEmits(['update:modelValue', 'confirm']);

const visible = ref(false);
const treeRef = ref();

watch(() => props.modelValue, (val) => {
  visible.value = val;
});

watch(visible, (val) => {
  emit('update:modelValue', val);
});

const treeProps = {
  children: 'children',
  label: props.labelProp
};

const cancel = () => {
  visible.value = false;
};

const confirm = () => {
  const checkedNodes = treeRef.value.getCheckedNodes();
  emit('confirm', checkedNodes.map(n => n[props.keyProp]));
  visible.value = false;
};
</script>
